﻿#include "BaseItemManager.h"
#include "BaseGraphicsItem.h"
#include "GraphicsDef.h"
#include <QGraphicsView>
#include <QGraphicsSceneMouseEvent>
#include <QFocusEvent>

namespace OfUI {

	BaseItemManager::BaseItemManager(QGraphicsScene* pScene, QObject *parent)
		: QObject(parent)
		, m_pScene(pScene)
		, m_pSelectItem(nullptr)
		, m_nAddType(NONE_TYPE)
	{
	}

	BaseItemManager::~BaseItemManager()
	{
	}

	void BaseItemManager::setAddType(int nType)
	{
		m_nAddType = nType;
	}

	void BaseItemManager::setSelected(BaseGraphicsItem* pItem)
	{
		if (m_pSelectItem == pItem)
		{
			return;
		}

		if (m_pSelectItem && m_pSelectItem != pItem)
		{
			m_pSelectItem->setState(BaseGraphicsItem::STATE_NORMAL);
		}
		m_pSelectItem = pItem;
		m_pSelectItem->setState(BaseGraphicsItem::STATE_SELECT);
	}

	void BaseItemManager::clearSelected()
	{
		if (m_pSelectItem)
		{
			m_pSelectItem->setState(BaseGraphicsItem::STATE_NORMAL);
			m_pSelectItem = nullptr;
		}
	}

	void BaseItemManager::removeItem(BaseGraphicsItem* pItem)
	{
		if (pItem == m_pSelectItem)
		{
			m_pSelectItem = nullptr;
		}
		pItem->setState(BaseGraphicsItem::STATE_NORMAL);

		m_pScene->removeItem(pItem);
		m_itemList.removeOne(pItem);
		delete pItem;
		pItem = nullptr;
	}

	void BaseItemManager::removeAll()
	{
		while (m_itemList.count() > 0)
		{
			removeItem(m_itemList.at(0));
		}
	}
	void BaseItemManager::mousePressEvent(QGraphicsSceneMouseEvent *event)
	{
		if (m_pSelectItem && m_pSelectItem->isEditing())
		{
			m_pSelectItem->mousePressEvent(event);
		}
		else
		{
			if (Qt::LeftButton == event->button())
			{
				BaseGraphicsItem* pItem = select(event->scenePos());
				if (!pItem)
				{
					pItem = createItem();
				}
				if (pItem)
				{
					setSelected(pItem);
					pItem->mousePressEvent(event);
					return;
				}
			}
			clearSelected();
		}
	}

	void BaseItemManager::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
	{
		if (m_pSelectItem)
		{
			m_pSelectItem->mouseReleaseEvent(event);
		}

		if (Qt::LeftButton != event->button())
		{
			clearSelected();
		}
	}

	void BaseItemManager::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
	{
		if (m_pSelectItem && m_pSelectItem->isEditing())
		{
			m_pSelectItem->mouseMoveEvent(event);
		}
		else
		{
			QCursor cursor = createCursor();
			BaseGraphicsItem* pItem = select(event->scenePos());

			if (pItem)
			{
				pItem->cursor(event->scenePos(), cursor);
			}
			m_pScene->views().at(0)->setCursor(cursor);
		}
	}

	void BaseItemManager::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
	{
		BaseGraphicsItem* pItem = select(event->scenePos());
		if (pItem)
		{
			pItem->mouseDoubleClickEvent(event);
		}
	}

	void BaseItemManager::focusOutEvent(QFocusEvent *event)
	{
		if (m_pSelectItem)
		{
			m_pSelectItem->focusOutEvent(event);
		}
	}

	QCursor BaseItemManager::createCursor() const
	{
		return Qt::ArrowCursor;
	}

}
